<?php

namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\SalePricerule;
use think\Cache;

class SalePricedb extends Model
{
    use SoftDelete;

    public $param = array();

    protected $name = 'sale_price';

    protected $pk = 'sale_price_id';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'sale_price_sign'
    ];

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (!isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function getHuoyuanAttr($value){
        return $value?$value:'';
    }

    // 自动完成唯一标识
    protected function setSalePriceSignAttr($value)
    {
        if ($value) {
            return $value;
        }
        return md5(time() . uniqid());
    }

    // 修改器
    public function setApiPriceAttr($value, $data)
    {
        if (!isset($data['category_sign3'])) {
            $goodsdb = new Goodsdb();
            $goodsdb->param['goods_sku'] = $data['goods_sku'];
            $get_goods = $goodsdb->ajaxFind();
            $data['category_sign3'] = $get_goods['category_sign3'];
        }
        // 反向查找分类折扣
        $categorydb = new Categorydb();
        $category_data = $categorydb->ajaxFind($data['category_sign3']);
        if (isset($category_data['site_rate'])) {
            $site_rate = $category_data['site_rate'];
            if ($value > $data['sale_price'] * $site_rate / 100) {
                return $data['sale_price'] * $site_rate / 100;
            } else {
                return $value;
            }
        } else {
            return $value;
        }
    }

    // 查询商品编号
    public function scopeGoodsSku($query, $goods_sku)
    {
        $query->where('goods_sku', 'IN', $goods_sku);
    }

    public function scopeSalePriceSign($query, $sale_price_sign)
    {
        $query->where('sale_price_sign', $sale_price_sign);
    }

    // 基础查询
    public function base($query)
    {
        /*
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        */
        /*$query->where('partner_id', PARTNER_ID);
        if (isset($this->param['site_id'])) {
            if ($this->param['site_id'] == 0 || $this->param['site_id'] == '') {
                $query->where('site_id', null);
            } elseif ($this->param['site_id'] != -1) {
                $query->where('site_id', $this->param['site_id']);
            }
        } else {
            if (!empty(SITE_ID)) {
                $query->where('site_id', SITE_ID);
            } else {
                $query->where('site_id', 'null');
            }
        }*/
        if (isset($this->param['goods_sku'])) {
            $query->goodsSku($this->param['goods_sku']);
        }
        if (isset($this->param['sale_price_sign']) && $this->param['sale_price_sign']) {
            $query->salePriceSign($this->param['sale_price_sign']);
        }
    }

    public function copy()
    {
        $data = $this->select();

        if (!$data->isEmpty()) {
            $data = $data->toArray();
            $add_data = array();
            if ($this->param['select_site_id'] == '') {
                $this->param['site_id'] = SITE_ID;
            } else {
                $this->param['site_id'] = $this->param['select_site_id'];
            }
            $this->ajaxDelete();
            foreach ($data as $key => $val) {
                unset($val['create_time']);
                unset($val['delete_time']);
                unset($val['sale_price_id']);
                unset($val['update_time']);
                $val['market_price'] = floatval($val['market_price']);
                $val['sale_price'] = floatval($val['sale_price']);
                $val['api_price'] = floatval($val['api_price']);
                $val['site_id'] = $this->param['site_id'];
                $this->insert($val);
            }
        }
    }

    public function collect()
    {
        $data = $this->select();

        if (!$data->isEmpty()) {
            $data = $data->toArray();
            $add_data = array();
            foreach ($data as $key => $val) {
                unset($val['create_time']);
                unset($val['delete_time']);
                unset($val['sale_price_id']);
                unset($val['update_time']);
                unset($val['site_id']);
                $val['market_price'] = floatval($val['market_price']);
                $val['sale_price'] = floatval($val['sale_price']);
                $val['api_price'] = floatval($val['api_price']);
                $this->insert($val);
            }
        }
    }

    public function ajaxSelect()
    {
        if (!isset($this->param['no_more_price'])) {
            $return['data'] = $this->ajaxList();
            $return['count'] = $this->ajaxCount();
            if ($return['count'] == 0) {
                $return['view_stock'] = 9999;
                $return['min_market_price'] = 0;
                $return['max_market_price'] = 0;
                $return['min_sale_price'] = 0;
                $return['max_sale_price'] = 0;
                $return['min_api_price'] = 0;
                $return['max_api_price'] = 0;
                $return['caigoujia'] = 0;
                $return['zuidijia'] = 0;
                $return['jun_zuidijia'] = 0;
                $return['chengbenjia'] = 0;
                $return['beizhu'] = '';
                $return['huoyuan'] = '';
            } else {
                $return['view_stock'] = $return['data'][0]['view_stock'];
                $return['caigoujia'] = $return['data'][0]['caigoujia'];
                $return['zuidijia'] = $return['data'][0]['zuidijia'];
                $return['jun_zuidijia'] = $return['data'][0]['jun_zuidijia'];
                $return['chengbenjia'] = $return['data'][0]['chengbenjia'];
                $return['beizhu'] = $return['data'][0]['beizhu'];
                $return['huoyuan'] = $return['data'][0]['huoyuan'];
                $return['min_market_price'] = $this->minMarketPrice();
                $return['max_market_price'] = $this->maxMarketPrice();
                $return['min_sale_price'] = $this->minSalePrice();
                $return['max_sale_price'] = $this->maxSalePrice();
                $return['min_api_price'] = $this->minApiPrice();
                $return['max_api_price'] = $this->maxApiPrice();
            }
        } else {
            $data = $this->order('sale_price_id desc')
                ->field('view_stock,market_price,sale_price,api_price,zuidijia,jun_zuidijia,caigoujia,chengbenjia,beizhu,huoyuan')
                ->find();
            if (!$data) {
                // 没有数据 重新初始化
                $save_data['partner_id'] = PARTNER_ID;
                $save_data['site_id'] = SITE_ID;
                $save_data['goods_sku'] = $this->param['goods_sku'];
                $save_data['market_price'] = 0;
                $save_data['sale_price'] = 0;
                $save_data['api_price'] = 0;
                $save_data['give_score'] = 0;
                $save_data['view_stock'] = 0;
                $save_data['caigoujia'] = 0;
                $save_data['zuidijia'] = 0;
                $save_data['jun_zuidijia'] = 0;
                $save_data['chengbenjia'] = 0;
                $save_data['beizhu'] = '';
                $save_data['huoyuan']= '';
                $save_data['sale_attr_price_name'] = '商品价格';
                $save_data['create_time'] = time();
                $save_data['sale_price_sign'] = md5(time() . uniqid());
                $this->insert($save_data);
                Cache::clear('sale_price');
                $return['data'][0] = array();
                $return['count'] = 0;
                $return['view_stock'] = 0;
                $return['min_market_price'] = 0;
                $return['min_sale_price'] = 0;
                $return['min_api_price'] = 0;
                $return['caigoujia'] = 0;
                $return['zuidijia'] = 0;
                $return['jun_zuidijia'] = 0;
                $return['chengbenjia'] = 0;
                $return['beizhu'] = '';
                $return['huoyuan'] = '';
            } else {
                $data = $data->toArray();
                $return['data'][0] = $data;
                $return['count'] = 1;
                $return['view_stock'] = $data['view_stock'];
                $return['min_market_price'] = $data['market_price'];
                $return['min_sale_price'] = $data['sale_price'];
                $return['min_api_price'] = $data['api_price'];
                $return['caigoujia'] = $data['caigoujia'];
                $return['zuidijia'] = $data['zuidijia'];
                $return['jun_zuidijia'] = $data['jun_zuidijia'];
                $return['chengbenjia'] = $data['chengbenjia'];
                $return['beizhu'] = $data['beizhu'];
                $return['huoyuan'] = $data['huoyuan'];
            }
        }

        return $return;
    }

    public function ajaxCount()
    {
        $count = $this->cache($this->cache_name('sale_price_count'), 86400, 'sale_price')
            ->count();
        return $count;
    }

    public function minMarketPrice()
    {
        return $this->cache($this->cache_name('sale_price_min_market_price'), 86400, 'sale_price')
            ->min('market_price');
    }

    public function maxMarketPrice()
    {
        return $this->cache($this->cache_name('sale_price_max_market_price'), 86400, 'sale_price')
            ->max('market_price');
    }

    public function minSalePrice()
    {
        return $this->cache($this->cache_name('sale_price_min_sale_price'), 86400, 'sale_price')
            ->min('sale_price');
    }

    public function maxSalePrice()
    {
        return $this->cache($this->cache_name('sale_price_max_sale_price'), 86400, 'sale_price')
            ->max('sale_price');
    }

    public function minApiPrice()
    {
        return $this->cache($this->cache_name('sale_price_main_api_price'), 86400, 'sale_price')
            ->min('api_price');
    }

    public function maxApiPrice()
    {
        return $this->cache($this->cache_name('sale_price_max_api_price'), 86400, 'sale_price')
            ->max('api_price');
    }

    // 查询
    public function ajaxList()
    {
        $data = $this->master(true)
            ->order('create_time asc')
            ->cache($this->cache_name('sale_price_list'), 86400, 'sale_price')
            ->select();
        if (!$data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    // 保存数据
    public function ajaxSave()
    {
        $this->ajaxDelete();
        // 验证传入的数组长度是否一致
        if (isset($this->param['sale_attr_price_name']) && isset($this->param['market_price']) && isset($this->param['sale_price'])) {
            if ((count($this->param['sale_attr_price_name']) == count($this->param['market_price'])) && (count($this->param['market_price']) == count($this->param['sale_price']))) {
                // 说明 这里市场价格>=销售价格>=接口价格
                $data = array();
                $rule = new SalePricerule();
                for ($i = 0; $i < count($this->param['sale_attr_price_name']); $i++) {
                    $data[$i]['goods_sku'] = $this->param['goods_sku'];
                    $data[$i]['market_price'] = $this->param['market_price'][$i];
                    $data[$i]['sale_price'] = $this->param['sale_price'][$i];
                    $data[$i]['api_price'] = $this->param['api_price'][$i];
                    $data[$i]['give_score'] = $this->param['give_score'][$i];
                    $data[$i]['view_stock'] = $this->param['view_stock'][$i];
                    $data[$i]['sale_attr_price_name'] = $this->param['sale_attr_price_name'][$i];
                    $data[$i]['category_sign3'] = $this->param['category_sign3'];
                    $data[$i]['site_id'] = $this->param['site_id'];
                    $data[$i]['last_api_price'] = isset($this->param['last_api_price']) ? $this->param['last_api_price'][$i] : 0;
                    $data[$i]['caigoujia'] = $this->param['caigoujia'][$i];
                    $data[$i]['chengbenjia'] = $this->param['chengbenjia'][$i]??0;
                    $data[$i]['beizhu'] = $this->param['beizhu'][$i]??'';
                    $data[$i]['huoyuan'] = $this->param['huoyuan'][$i]??'';
                    if (!$rule->check($data[$i])) {
                        return $rule->getError();
                    }
                }
                $data_all = $this->allowField(true)->saveAll($data);
                Cache::clear('sale_price');
                return 'success';
            } else {
                return '数据错误，销售价格数据对应不上，请联系管理员';
            }
        } else {
            return '销售价格必须填写';
        }
    }

    public function ajaxSaveFieldValue()
    {
        $value = $this->find()->toArray();
        $value[$this->param['field']] = $this->param['value'];
        $value['category_sign3'] = $this->param['category_sign3'];
        if ($value['market_price'] < $value['sale_price']) {
            $value['sale_price'] = $value['market_price'];
        }
        unset($value['create_time']);
        unset($value['delete_time']);
        $this->save($value, function ($query) {
            if ($this->param['site_id'] == '' || $this->param['site_id'] == 0) {
                $query->where('site_id', 'null');
            } else {
                $query->where('site_id', $this->param['site_id']);
            }
            $query->where('sale_price_sign', $this->param['sale_price_sign']);
            $query->where('goods_sku', $this->param['goods_sku']);
        });
        Cache::clear('sale_price');
        return 'success';
    }

    public function ajaxFind()
    {
        $data = $this->find();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data = array();
        }
        return $data;
    }

    // 直接删除
    public function ajaxDelete()
    {
        if (isset($this->param['site_id'])) {
            $this->where('site_id', $this->param['site_id'])->delete();
        } else {
            $this->where('goods_sku', $this->param['goods_sku'])->delete();
        }
        Cache::clear('sale_price');
    }

    // 数据处理
    protected function handleData($val)
    {
        $sitedb = new Sitedb();
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                default:
                    break;
            }
        }
        return $val;
    }
}